import React, { Component } from 'react';
import { routerRedux, Route, Switch, Link } from 'dva/router';
// import { routerRedux,Link } from 'dva/router';

// import { Radar, ChartCard } from 'ant-design-pro/lib/Charts';
// import Charts from 'ant-design-pro/lib/Charts';

import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import { connect } from 'dva';
import {
  Button, Menu, Dropdown, Icon, Row, Col,
  Input, InputNumber,
  Steps, Card, Popover, Badge, Table, Tooltip, Divider,
  Checkbox, Modal, Radio,
  Select, message, Timeline, Collapse,
  Form, Upload, Spin, Tag
} from 'antd';
import { Radar, ChartCard, Bar } from '../../components/Charts';
import classNames from 'classnames';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import DescriptionList from '../../components/DescriptionList';
import styles from './ApplyProfile.less';
import { create } from 'domain';
import u620 from '../../assets/u620.png';
import u622 from '../../assets/u622.png';
import querystring from 'querystring';
import { solo } from '../../common/solo';

import { getRoutes } from '../../utils/utils';
import { div } from 'gl-matrix/src/gl-matrix/vec3';

const Panel = Collapse.Panel;
const { Step } = Steps;
const TextArea = Input.TextArea;
const { Description } = DescriptionList;
const ButtonGroup = Button.Group;
const RadioGroup = Radio.Group;
const Option = Select.Option;

const getWindowWidth = () => (window.innerWidth || document.documentElement.clientWidth);

export let profileState = false;

@connect(({ pendingTask }) => ({
  pendingTask,
}))
@Form.create()
export default class ApplyDetails extends Component {
  state = {
    id: '',
    reviewState: '',
    stepDirection: 'horizontal',
    modalVisible: false,
    progressVisible: false,
    submitting: false,
    custList: {},
    taskList: {},
    radarData: [],
    auditList: [],
    approvalRecordList: [],
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    const params = querystring.parse(location.search.slice(1));
    // console.log("qqqqqAAAAAAAAparams.id")
    // console.log(params.id)
    this.setState({
      id: params.id,
      // state: params.state,
    });
    dispatch({
      type: 'pendingTask/fetchApplyProfile',
      payload: {
        id: params.id,
      },
      callback: () => {
        const { pendingTask: { custMessgeList, custTaskList, custListLoading } } = this.props;

        this.setState({
          custListLoading: custListLoading,
          custList: custMessgeList,
          taskList: custTaskList,
          // auditList: custAuditList
        })

        if (custTaskList.taskName == "初审") {
          this.setState({
            reviewState: 1,
          })
        } else if (custTaskList.taskName == "复审") {
          this.setState({
            reviewState: 2,
          })
        } else if (custTaskList.taskName == "终审") {
          this.setState({
            reviewState: 3,
          })
        }
        dispatch({
          type: 'pendingTask/showAllAudit',
          payload: {
            applyId: custMessgeList.id,
          },
          callback: () => {
            const { pendingTask: { auditsList } } = this.props;
            // console.log("audits",auditsList)
            this.setState({
              auditList: auditsList
            })
          }
        })
        dispatch({
          type: 'pendingTask/approvalRecord',
          payload: {
            applyId: custMessgeList.id,//"992290496124190722",//
          },
          callback: () => {
            const { pendingTask: { approvalRecordList, approvalLoading } } = this.props;
            if (approvalRecordList.length > 0) {
              this.setState({
                approvalRecordList: approvalRecordList,
              })
            }
          }
        });
      }
    });
    // if(this.state.reviewState !== 3 ){
    this.setStepDirection();
    window.addEventListener('resize', this.setStepDirection);
    // }  
  }

  // componentWillUnmount() {
  //   //   if(this.state.reviewState !== 3 ){
  //   window.removeEventListener('resize', this.setStepDirection);
  //   this.setStepDirection.cancel();
  //   // }
  // }

  @Bind()
  @Debounce(200)
  setStepDirection() {
    const { stepDirection } = this.state;
    const w = getWindowWidth();
    if (stepDirection !== 'vertical' && w <= 576) {
      this.setState({
        stepDirection: 'vertical',
      });
    } else if (stepDirection !== 'horizontal' && w > 576) {
      this.setState({
        stepDirection: 'horizontal',
      });
    }
  }

  handleTabChange = (key) => {
    const { dispatch, match } = this.props;
    switch (key) {
      case 'customer':
        dispatch(routerRedux.push(`/review/apply-details/step1?id=${this.state.id}&custId=${this.state.custList.id}&taskId=${this.state.taskList.id}&reviewState=${this.state.reviewState}`));
        break;
      case 'business':
        dispatch(routerRedux.push(`/review/apply-details/step2?id=${this.state.id}&custId=${this.state.custList.id}&taskId=${this.state.taskList.id}&reviewState=${this.state.reviewState}`));
        break;
      case 'credits':
        dispatch(routerRedux.push(`/review/apply-details/step3?id=${this.state.id}&custId=${this.state.custList.id}&taskId=${this.state.taskList.id}&reviewState=${this.state.reviewState}`));
        break;
      case 'pay':
        dispatch(routerRedux.push(`/review/apply-details/step4?id=${this.state.id}&custId=${this.state.custList.id}&taskId=${this.state.taskList.id}&reviewState=${this.state.reviewState}`));
        break;
      case 'guarantee':
        dispatch(routerRedux.push(`/review/apply-details/step5?id=${this.state.id}&custId=${this.state.custList.id}&taskId=${this.state.taskList.id}&reviewState=${this.state.reviewState}`));
        break;
      case 'suggestion':
        dispatch(routerRedux.push(`/review/apply-details/step6?id=${this.state.id}&custId=${this.state.custList.id}&taskId=${this.state.taskList.id}&reviewState=${this.state.reviewState}`));
        break;
      default:
        break;
    }
  }



  tabList = [{
    key: 'customer',
    tab: '客户信息核实',
  }, {
    key: 'business',
    tab: '业务情况核实',
  }, {
    key: 'credits',
    tab: '资信情况调查',
  }, {
    key: 'pay',
    tab: '还款能力调查',
  }, {
    key: 'guarantee',
    tab: '担保情况调查',
  }, {
    key: 'suggestion',
    tab: '审核意见',
  }
  ];

  handleProgress = () => {
    this.state.approvalRecordList.length > 0 ?
      this.setState({
        progressVisible: true
      })
      :
      message.warning("暂无审批记录")
  }

  handleProgressModalCancel = () => {
    this.setState({
      progressVisible: false
    })
  }
  hanleProgressModalOk = () => {
    this.setState({
      progressVisible: false
    })
  }
  handleClickShow = () => {
    this.setState({
      modalVisible: true
    })
  }
  hanleCreateUserModalOk = () => {
    this.setState({
      modalVisible: false
    })
  }
  handleModalCancel = () => {
    this.setState({
      modalVisible: false
    })
  }

  progressColumns = [
    {
      title: '指标',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: '初审',
      dataIndex: 'state1',
      key: 'state1',
      render: (text, item) => {
        return (<div>
          {
            item.childrens.map((child) => {

              if (child.state1 == 1) {
                return <Tag color='green'>{child.name}  <Icon type="check" style={{ color: 'green' }} /></Tag>;
              }
              if (child.state1 == 2) {
                return <Tag color='red'>{child.name} <Icon type="close" style={{ color: 'red' }} /></Tag>;
              }
              if (child.state1 == null) {
                if (child.name == "偿债意愿核实") {
                  return;
                }
                return <Tag >{child.name} <Icon type="minus" style={{ color: 'gray' }} /></Tag>;
              }
            })}
        </div>);
      }
    },
    {
      title: '复审',
      dataIndex: 'state2',
      key: 'state2',
      render: (text, item) => {
        return (<div>
          {
            item.childrens.map((child) => {

              if (child.state2 == 1) {
                return <Tag color='green'>{child.name}  <Icon type="check" style={{ color: 'green' }} /></Tag>;
              }
              if (child.state2 == 2) {
                return <Tag color='red'>{child.name} <Icon type="close" style={{ color: 'red' }} /></Tag>;
              }
              if (child.state2 == null) {
                return <Tag >{child.name} <Icon type="minus" style={{ color: 'gray' }} /></Tag>;
              }
            })}
        </div>);
      }
    },
  ];

  renderDescription = () => {
    return (
      this.state.custList &&
      // <Row>
      //   <Col xs={24} sm={16}>
      <DescriptionList className={styles.headerList} size="small" col="3">
        <Description term="客户名称">{this.state.custList.custName}</Description>
        <Description term="证件号">{this.state.custList.idno}</Description>
        <Description term="担保公司">{this.state.custList.orgName}</Description>
        <Description term="经销商">{this.state.custList.dealer}</Description>
        <Description term="所购车型">{this.state.custList.carType}</Description>
        <Description term="车辆类型">{this.state.custList.carClass == 1 ? "新车" : "二手车"}</Description>
        <Description term="车价">{this.state.custList.carPrice}</Description>
        <Description term="分期金额">{this.state.custList.loanAmount}</Description>
        <Description term="分期数">{this.state.custList.duration}</Description>
      </DescriptionList>
    );
  };

  renderExtraContent = () => {
    return (
      <Row >
        <Col xs={24} sm={8}>
          <div className={styles.textSecondary}>车价</div>
          <div className={styles.heading}>{this.state.custList.carPrice}</div>
        </Col>
        <Col xs={24} sm={8}>
          <div className={styles.textSecondary}>分期金额</div>
          <div className={styles.heading}>{this.state.custList.loanAmount}</div>
        </Col>
        <Col xs={24} sm={8}>
          <div className={styles.textSecondary}>分期数</div>
          <div className={styles.heading}>{this.state.custList.duration}</div>
        </Col>
      </Row>
    );
  };

  render() {
    const { stepDirection } = this.state;
    const { getFieldDecorator, getFieldValue } = this.props.form;

    const { match, routerData, location } = this.props;
    const routes = getRoutes(match.path, routerData);
    const img = (<img alt="" src={u620} width={10} />);
    const { pathname, params, search } = location;

    let approvalId = 0;

    let tabActiveKey = 'customer';
    if (pathname.indexOf('step2') > -1) {
      tabActiveKey = 'business';
    } else if (pathname.indexOf('step3') > -1) {
      tabActiveKey = 'credits';
    } else if (pathname.indexOf('step4') > -1) {
      tabActiveKey = 'pay';
    } else if (pathname.indexOf('step5') > -1) {
      tabActiveKey = 'guarantee';
    } else if (pathname.indexOf('step6') > -1) {
      tabActiveKey = 'suggestion';
    }

    const { pendingTask: { auditStatusList, approvalLoading } } = this.props;

    const menu = (
      <Menu >
        <Menu.Item key="1" >
          <a
            target="_blank"
            // href={`http://f2c-api.yunqian99.com/v1/apply/downloadPdf/${this.state.custList.id}`}>
             href={`${solo.pdfDownloadUrl}${this.state.custList.id}`}>
            {/*href={`http://192.168.2.154:9050/v1/apply/downloadPdf/${this.state.custList.id}`}> */}
            调查报告下载
          </a>
        </Menu.Item>
      </Menu>
    );
    const action = (
      <div>
        <ButtonGroup>
          <Button onClick={this.handleClickShow}>审批结果</Button>
          <Button onClick={this.handleProgress}>审批记录</Button>
          <Dropdown overlay={menu} placement="bottomRight">
            <Button><Icon type="ellipsis" /></Button>
          </Dropdown>
        </ButtonGroup>
      </div>
    );
    const description = this.renderDescription();
    // const extra = this.renderExtraContent();

    return (
      <PageHeaderLayout
        title="基本信息"
        logo={<img alt="" src="https://gw.alipayobjects.com/zos/rmsportal/nxkuOJlFJuAUhzlMTCEe.png" />}
        content={description}
        tabList={this.tabList}
        tabActiveKey={tabActiveKey}
        // extraContent={extra}
        onTabChange={this.handleTabChange}
        action={action}
      >
        {/* {JSON.stringify(this.state.auditList)} */}
        {this.state.reviewState == 3 ?
          null
          :
          <Col span={3}>
            客户信息核实 {auditStatusList[0] == true ? img : ""}<br /><br />
            业务情况核实 {auditStatusList[1] == true ? img : ""}<br /><br />
            资信情况调查 {auditStatusList[2] == true ? img : ""}<br /><br />
            还款能力调查 {auditStatusList[3] == true ? img : ""}<br /><br />
            担保情况调查 {auditStatusList[4] == true ? img : ""}<br /><br />
            {/* <Button type="primary" onClick={this.handleClickShow}>审批详情</Button> */}
          </Col>
        }

        <Col span={21}>
          <Switch>
            {
              routes.map(item =>
                (
                  <Route
                    key={item.key}
                    path={item.path}
                    component={item.component}
                    exact={item.exact}
                  />
                )
              )
            }
          </Switch>
        </Col>
        <Modal
          title={'审批结果'}
          visible={this.state.modalVisible}
          footer={null}
          keyboard={true}
          onCancel={this.handleModalCancel}
          cancelText={null}
        >
          <Table
            // title={title}
            columns={this.progressColumns}
            dataSource={this.state.auditList.all}
            size="small"
            rowKey="key"
            bordered={false}
            pagination={false}
            style={{ marginBottom: 20 }}
          />
        </Modal>
        <Modal
          title='审批记录'
          keyboard={true}
          footer={null}
          visible={this.state.progressVisible}
          onCancel={this.handleProgressModalCancel}
        >
          <Collapse>
            {
              approvalLoading ?
                <div className={styles.spinContainer}>
                  <Spin size="large" />
                </div>
                :
                this.state.approvalRecordList && this.state.approvalRecordList.map((item) => {
                  return (
                    <Panel header={item.displayName + "  " + item.finishTime} key={item.id}>
                      <p>任务名称：{item.displayName}</p>
                      <p>创建时间：{item.createTime}</p>
                      <p>完成时间：{item.finishTime}</p>
                      <p>任务处理人：{item.opname}</p>
                      <p>任务处理结果：{item.result}</p>
                      <p>意见：{item.content}</p>
                    </Panel>
                  )
                })
            }
          </Collapse>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
